const express = require('express');

const router = express.Router();

const Dept = require('../models/Dept.js');

// GET `/dept/list`
router.get( '/dept/list' , (req,resp) => {
    Dept.findAll().then( rows => rows.map( row => row.dataValues ) )
    .then( depts => {
        resp.render( 'dept/list' , { depts: depts });
    }).catch( reason => {
        resp.render( 'dept/list' , { reason: reason });
    })
});

// GET `/dept/add`
router.get( '/dept/add' , (req,resp) => {
    resp.render( 'dept/add' );
});

// POST `/dept/add`
router.post( '/dept/add' , (req,resp) => {
    let { deptName } = req.body ;
    Dept.create( { name: deptName } ).then( dept => {
        dept = dept.dataValues ;
        console.log( '由数据库产生的主键: ' , dept.id );
        resp.redirect( '/dept/list' );
    }).catch( reason => {
        resp.redirect( '/dept/add' );
    })
});

module.exports = router;